import cv2


# MSR
def replaceZeroes(data):
    min_nonzero = min(data[nonzero(data)])
    data[data == 0] = min_nonzero
    return data


def MSR(img, scales):
    weight = 1 / 3.0
    scales_size = 3

    h, w = img.shape[:2]
    dst_img = zeros((h, w), dtype=float32)
    dst_Lblur = zeros((h, w), dtype=float32)
    dst_R = zeros((h, w), dtype=float32)
    log_R = zeros((h, w), dtype=float32)

    for i in range(0, scales_size):
        img = replaceZeroes(img)
        L_blur = cv2.GaussianBlur(img, (scales[i], scales[i]), 0)
        L_blur = replaceZeroes(L_blur)
        cv2.log(img, dst_img)
        cv2.log(L_blur, dst_Lblur)
        log_R += weight * cv2.subtract(dst_img, dst_Lblur)

    cv2.normalize(log_R, dst_R, 0, 255, cv2.NORM_MINMAX)
    log_uint8 = cv2.convertScaleAbs(dst_R)

    return log_uint8


